package com.zhuangjie.mvc.ws.core;

import com.zhaungjie.base.utils.json.JsonUtils;
import com.zhuangjie.event.annotation.ModuleEventName;
import com.zhuangjie.event.service.AbstractModuleEventService;
import com.zhuangjie.mvc.ws.entity.WSEventData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;

import java.io.IOException;

@ModuleEventName(moduleNamePrefix = true)
public class WSEvent extends AbstractModuleEventService {
    @Autowired
    private WebSocketSessionStore sessionStore;

    /**
     * 监听其它节点要委托发送的消息
     *
     * @param message 消息
     * @param pattern 图案
     */
    @Override
    public void on(Message message, byte[] pattern) {
        String json = new String(message.getBody());
        WSEventData wsEventData = JsonUtils.parse(json, WSEventData.class);
        try {
            sessionStore.sendMessage(wsEventData.getKey(),wsEventData.getData(), wsEventData.getIds());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
